<template>
  <div class="filter-container">
    <el-container>
      <!-- 左侧筛选区域 -->
      <el-aside width="280px" class="filter-side">
        <!-- 房型筛选 -->
        <div class="filter-group">
          <h3 class="filter-title">房型筛选</h3>
          <el-select
            v-model="activeFilters.roomType"
            placeholder="请选择房型"
            class="full-width-select"
          >
            <el-option label="全部房型" value="all" />
            <el-option
              v-for="item in roomTypes"
              :key="item.value"
              :label="`${item.label} (${item.count})`"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 房态筛选 -->
        <div class="filter-group">
          <h3 class="filter-title">房态筛选</h3>

          <div class="vertical-button-group">
            <el-button
              v-for="clean in dynamicCleanStatus"
              :key="clean.value"
              :type="activeFilters.cleanStatus === clean.value ? 'primary' : ''"
              @click="activeFilters.cleanStatus = clean.value"
            >
              {{ clean.label }} ({{ clean.count }})
            </el-button>
          </div>
        </div>

        <!-- 清洁状态 -->
        <div class="filter-group">
          <h3 class="filter-title">清洁状态</h3>
          <div class="vertical-button-group">
            <el-button
              v-for="status in dynamicRoomStatus"
              :key="status.value"
              :type="activeFilters.roomStatus === status.value ? 'primary' : ''"
              @click="activeFilters.roomStatus = status.value"
            >
              <el-icon><Search /></el-icon>
              {{ status.label }} ({{ status.count }})
            </el-button>
          </div>
        </div>
      </el-aside>

      <!-- 右侧结果区域 -->
      <el-main class="result-area">
        <!-- 按房型分组显示 -->
        <div
          v-for="(rooms, typeId) in groupedRooms"
          :key="typeId"
          class="room-group"
        >
          <h3 class="room-type-title">{{ getRoomTypeName(typeId) }}</h3>
          <el-row :gutter="16">
            <el-col
              v-for="room in rooms"
              :key="room.number"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              :xl="4"
            >
              <div class="room-card">
                <!-- 操作菜单 -->
                <el-dropdown
                  trigger="click"
                  class="room-menu"
                  @command="handleMenuCommand($event, room)"
                >
                  <div class="menu-trigger">
                    <el-icon :size="16"><MoreFilled /></el-icon>
                  </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        command="detail"
                        :icon="View"
                        @click="Jumpto(1, room.number)"
                      >
                        办理入住
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="edit"
                        :icon="Edit"
                        @click="Jumpto(2, room.number)"
                      >
                        办理预定
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="edit"
                        :icon="Edit"
                        @click="Jumpto(3, room.number)"
                      >
                        办理退房
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="delete"
                        :icon="Delete"
                        @click="Jumpto(1, room.number)"
                      >
                        设为脏房
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="delete"
                        :icon="Delete"
                        @click="Jumpto(1, room.number)"
                      >
                        设为维修
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>

                <!-- 房间信息展示 -->
                <div class="room-info">
                  <h3>{{ room.number }}</h3>
                  <div class="status-display">
                    <span class="status-text">{{
                      roomStatusMap.get(room.status)
                    }}</span>

                    <span class="clean-status">{{ room.roomType }}</span>
                    <span class="clean-status">{{ room.status }}</span>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Search,
  MoreFilled,
  View,
  Edit,
  Delete,
} from "@element-plus/icons-vue";

import {
  getroomTypes,
  GetExtrRCRoomState,
  getRCRoomNewState,
  GetRCRoomNnmber,
} from "@/api/RoomConditionManagement/RoomCM.ts";

// 路由
const router = useRouter();
const route = useRoute();
// 类型定义 ----------------------------------------------------------------
interface FilterOption {
  value: string;
  label: string;
  count: number;
}

interface RoomInfo {
  number: string;
  type: string; // 房型ID
  status: string; // 房态值（vacant/occupied等）
  roomType: string; // 清洁状态（clean/gym等）
}

const Jumpto = (num: number, roomNumber: any) => {
  if (num == 1) {
    router.push({
      path: "/RoomStatus/RoomReservation",
      query: {
        roomNumber: roomNumber,
      },
    });
  }
  if (num == 2) {
    router.push("/RoomStatus/RoomReservation");
  }
};

// 响应式数据 --------------------------------------------------------------
const sourceRooms = ref<RoomInfo[]>([]);
const activeFilters = reactive({
  roomType: "all",
  roomStatus: "all",
  cleanStatus: "all",
});

// 从API获取的原始筛选选项
const roomTypes = ref<FilterOption[]>([]);
const roomStatusOptions = ref<FilterOption[]>([]);
const cleanStatusOptions = ref<FilterOption[]>([]);

// 映射表用于显示友好名称
const roomStatusMap = computed(
  () => new Map(roomStatusOptions.value.map((item) => [item.value, item.label]))
);

const cleanStatusMap = computed(
  () =>
    new Map(cleanStatusOptions.value.map((item) => [item.value, item.label]))
);

// 动态计算筛选选项（前端添加"全部"选项）
// 动态计算房间状态筛选选项（前端添加"全部"选项）
const dynamicRoomStatus = computed(() => {
  // 计算"全部"选项的数量（需同时满足以下条件）：
  // 1. 房型匹配：当前房型筛选为"全部" 或 房间类型匹配选中房型
  // 2. 清洁状态匹配：当前清洁筛选为"全部" 或 房间的清洁状态匹配选中状态
  const allCount = sourceRooms.value.filter(
    (room) =>
      (activeFilters.roomType === "all" ||
        room.type === activeFilters.roomType) &&
      (activeFilters.cleanStatus === "all" ||
        room.roomType === activeFilters.cleanStatus)
  ).length;

  // 构建动态选项（每个状态选项的数量计算需同时满足）：
  // 1. 房间状态匹配当前遍历的状态选项
  // 2. 房型匹配：当前房型筛选为"全部" 或 房间类型匹配选中房型
  // 3. 清洁状态匹配：当前清洁筛选为"全部" 或 房间的清洁状态匹配选中状态
  return [
    { value: "all", label: "全部", count: allCount },
    ...roomStatusOptions.value.map((status) => ({
      ...status,
      count: sourceRooms.value.filter(
        (room) =>
          room.status === status.value &&
          (activeFilters.roomType === "all" ||
            room.type === activeFilters.roomType) &&
          (activeFilters.cleanStatus === "all" ||
            room.roomType === activeFilters.cleanStatus)
      ).length,
    })),
  ];
});

// 动态计算清洁状态筛选选项（前端添加"全部"选项）
const dynamicCleanStatus = computed(() => {
  // 计算"全部"选项的数量（需同时满足以下条件）：
  // 1. 房型匹配：当前房型筛选为"全部" 或 房间类型匹配选中房型
  // 2. 房间状态匹配：当前房间状态筛选为"全部" 或 房间状态匹配选中状态
  const allCount = sourceRooms.value.filter(
    (room) =>
      (activeFilters.roomType === "all" ||
        room.type === activeFilters.roomType) &&
      (activeFilters.roomStatus === "all" ||
        room.status === activeFilters.roomStatus)
  ).length;

  // 构建动态选项（每个清洁选项的数量计算需同时满足）：
  // 1. 清洁状态匹配当前遍历的清洁选项
  // 2. 房型匹配：当前房型筛选为"全部" 或 房间类型匹配选中房型
  // 3. 房间状态匹配：当前房间状态筛选为"全部" 或 房间状态匹配选中状态
  return [
    { value: "all", label: "全部", count: allCount },
    ...cleanStatusOptions.value.map((clean) => ({
      ...clean,
      count: sourceRooms.value.filter(
        (room) =>
          room.roomType === clean.value &&
          (activeFilters.roomType === "all" ||
            room.type === activeFilters.roomType) &&
          (activeFilters.roomStatus === "all" ||
            room.status === activeFilters.roomStatus)
      ).length,
    })),
  ];
});

// 综合过滤后的房间数据（需同时满足三个维度条件）：
// 1. 房型匹配：当前房型筛选为"全部" 或 房间类型匹配选中房型
// 2. 房间状态匹配：当前房间状态筛选为"全部" 或 房间状态匹配选中状态
// 3. 清洁状态匹配：当前清洁筛选为"全部" 或 房间清洁状态匹配选中状态
const filteredRooms = computed(() => {
  return sourceRooms.value.filter((room) => {
    const typeMatch =
      activeFilters.roomType === "all" || room.type === activeFilters.roomType;
    const statusMatch =
      activeFilters.roomStatus === "all" ||
      room.status === activeFilters.roomStatus;
    const cleanMatch =
      activeFilters.cleanStatus === "all" ||
      room.roomType === activeFilters.cleanStatus;
    return typeMatch && statusMatch && cleanMatch;
  });
});

// 按房型分组显示（基于已过滤的房间数据）
const groupedRooms = computed(() => {
  return filteredRooms.value.reduce((groups, room) => {
    const typeKey = room.type; // 使用房间的type字段作为分组键
    if (!groups[typeKey]) groups[typeKey] = [];
    groups[typeKey].push(room);
    return groups;
  }, {} as Record<string, RoomInfo[]>);
});
// 数据初始化
const fetchData = async () => {
  try {
    const [typesRes, statusRes, cleanRes, roomsRes] = await Promise.all([
      getroomTypes(),
      GetExtrRCRoomState(), // 房态数据
      getRCRoomNewState(), // 清洁状态数据
      GetRCRoomNnmber(), // 房间列表
    ]);

    // 初始化数据（保持API原始结构）
    roomTypes.value = typesRes.data;
    roomStatusOptions.value = statusRes.data;
    cleanStatusOptions.value = cleanRes.data;

    // 处理房间数据
    if (roomsRes.code === 200) {
      sourceRooms.value = roomsRes.data.map((room: any) => ({
        ...room,
        type: room.type.toLowerCase(), // 统一转为小写
      }));
    }
  } catch (error) {
    console.error("数据加载失败:", error);
  }
};

// 获取房型名称
const getRoomTypeName = (typeId: string) => {
  const type = roomTypes.value.find((t) => t.value.toLowerCase() === typeId);
  return type?.label || "未知房型";
};

// 操作菜单处理
const handleMenuCommand = (command: string, room: RoomInfo) => {
  console.log(`执行操作 ${command}`, room.number);
  // 实际业务中这里添加具体逻辑
};

// 初始化加载数据
onMounted(fetchData);
</script>

<style scoped>
/* 通用样式 */
.full-width-select {
  width: 100%;
  margin-bottom: 16px;
}

.vertical-button-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.vertical-button {
  width: 100%;
  justify-content: flex-start;
  padding-left: 20px;
  margin: 4px 0 !important;
}

/* 容器样式 */
.filter-container {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  background: #fff;
}

.filter-side {
  padding: 20px;
  border-right: 1px solid #ebeef5;
  background: #f8f9fa;
}

.filter-title {
  color: #606266;
  margin: 16px 0;
}

/* 结果区域 */
.result-area {
  padding: 20px;
  min-height: 400px;
}

.el-col {
  padding: 10px;
}

/* 卡片样式 */
.room-card {
  position: relative;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
  height: 140px;
  overflow: hidden;
}

.room-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.room-info {
  padding: 16px;
  text-align: center;
}

/* 房间组样式 */
.room-group {
  margin-bottom: 32px;
}

.room-type-title {
  color: #606266;
  padding: 12px 0;
  border-bottom: 2px solid #ebeef5;
  margin-bottom: 16px;
}

/* 菜单样式 */
.room-menu {
  position: absolute;
  right: 8px;
  top: 8px;
  z-index: 10;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.room-menu:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

.menu-trigger {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
}

.room-status {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}

.status-display {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.status-text {
  color: #67c23a;
  font-size: 14px;
}
.clean-status {
  color: #909399;
  font-size: 12px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .room-card {
    width: 100%;
  }

  .room-info h3 {
    font-size: 20px;
    color: #303133;
    margin: 0 0 8px;
  }
}
</style>